<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>湾豚工单系统V2</title>
    <link rel="icon" href="/static/favicon.ico" type="image/x-icon">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css">

    <style>
        table {
            table-layout: fixed; /* 表格布局固定 */
            width: 100%; /* 表格占满容器宽度 */
        }

        table th, table td {
            white-space: nowrap; /* 防止内容换行 */
            text-overflow: ellipsis; /* 超出部分显示省略号 */
            overflow: hidden; /* 隐藏超出部分 */
        }

        /* 设置每一列的宽度 */
        table th:nth-child(1), table td:nth-child(1) { /* ID 列 */
            width: 60px;
        }

        table th:nth-child(2), table td:nth-child(2) { /* 标题列 */
            width: 120px;
        }

        table th:nth-child(3), table td:nth-child(3) { /* 描述列 */
            white-space: nowrap; /* 防止换行 */
            text-overflow: ellipsis; /* 超出部分显示省略号 */
            overflow: hidden; /* 隐藏超出部分 */
        }


        table th:nth-child(4), table td:nth-child(4) { /* 提交人列 */
            width: 65px;
        }

        table th:nth-child(5), table td:nth-child(5) { /* 状态列 */
            width: 70px;
            text-align: center;
        }

        table th:nth-child(6), table td:nth-child(6) { /* 操作列 */
            width: 180px;
            text-align: center;
        }
    </style>


</head>
<body>
<div class="container mt-4">
    <h1 class="text-center">湾豚工单系统V2</h1>
    <div class="d-flex justify-content-between mb-4">
        <!-- 创建工单按钮 -->
        <button id="create-ticket-btn" class="btn btn-primary">创建工单</button>
        <!-- 工单状态过滤下拉框，居右并放置在刷新按钮左边 -->
        <div class="d-flex justify-content-end align-items-center">
            <select id="ticket-status-filter" class="form-select w-auto" onchange="fetchTickets()">
                <option value="all">全部</option>
                <option value="open">已提交</option>
                <option value="in_progress">处理中</option>
                <option value="closed">已关闭</option>
            </select>

            <!-- 刷新工单列表按钮 -->
            <button id="refresh-btn" class="btn btn-secondary ms-2">刷新</button>
        </div>
    </div>
    <table class="table table-bordered">
        <thead>
        <tr>
            <th>ID</th>
            <th>标题</th>
            <th>描述</th>
            <th>提交人</th>
            <th>状态</th>
            <th>操作</th>
        </tr>
        </thead>
        <tbody id="ticket-table-body">
        <!-- 工单数据行将插入这里 -->
        </tbody>
    </table>
    <nav class="d-flex justify-content-between align-items-center">
    <!-- 上一页按钮 -->
    <button id="prev-page-btn" class="btn btn-secondary">上一页</button>

    <!-- 页码选择下拉框 -->
    <div class="d-flex align-items-center">
        <select id="page-select" class="form-select w-auto mx-2" onchange="changePage(this.value)">
            <!-- 页码选项将在 JS 中动态插入 -->
        </select>
        <span>共 <span id="total-pages">0</span> 页</span>
    </div>

    <!-- 下一页按钮 -->
    <button id="next-page-btn" class="btn btn-secondary">下一页</button>
</nav>

</div>

<!-- 模态框用于创建新工单 -->
<div class="modal" tabindex="-1" id="create-ticket-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">创建工单</h5>
                <!-- 关闭按钮 -->
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 创建工单表单 -->
                <form id="create-ticket-form">
                    <div class="mb-3">
                        <label for="title" class="form-label">标题</label>
                        <input type="text" class="form-control" id="title" required>
                    </div>
                    <div class="mb-3">
                        <label for="description" class="form-label">描述</label>
                        <textarea class="form-control" id="description" rows="3" required></textarea>
                    </div>
                    <div class="mb-3">
                        <label for="submitter" class="form-label">提交人</label>
                        <input type="text" class="form-control" id="submitter" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <!-- 关闭模态框按钮 -->
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <!-- 保存工单按钮 -->
                <button type="button" class="btn btn-primary" id="save-ticket-btn">保存</button>
            </div>
        </div>
    </div>
</div>

<!-- 模态框用于显示工单详情 -->
<div class="modal" tabindex="-1" id="view-ticket-modal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">查看工单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <!-- 工单信息展示 -->
                <p><strong>ID:</strong> <span id="ticket-id"></span></p>
                <p><strong>标题:</strong> <span id="ticket-title"></span></p>
                <p><strong>描述:</strong> <span id="ticket-description"></span></p>
                <p><strong>提交人:</strong> <span id="ticket-submitter"></span></p>
                <p><strong>受理人:</strong> <span id="ticket-assignee"></span></p>
                <p><strong>状态:</strong> <span id="ticket-status"></span></p>
                <p><strong>创建时间:</strong> <span id="ticket-create-time"></span></p>
                <p><strong>更新时间:</strong> <span id="ticket-update-time"></span></p>
                <p><strong>工单回复:</strong></p>
                <div class="mb-3">
                    <textarea class="form-control" id="ticket-recover" rows="4"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="save-recover-btn">提交</button>
            </div>
        </div>
    </div>
</div>



<!-- 引入 Bootstrap 的 JavaScript 库 -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/js/bootstrap.bundle.min.js"></script>
<script>
    // 动态获取当前域名和端口
    const apiBase = window.location.origin;  // 例如 http://127.0.0.1:8000

    // 工单状态枚举
    const ticketStatusEnum = {
        open: '已提交',
        in_progress: '处理中',
        closed: '已关闭',
    };

    // 获取并显示分页的工单
    async function fetchTickets(page = 1) {
        const statusFilter = document.getElementById('ticket-status-filter').value;  // 获取选择的状态
        const response = await fetch(`${apiBase}/tickets_paginated?page=${page}&status=${statusFilter}`);  // 向后台请求数据
        const data = await response.json();  // 解析返回的 JSON 数据
        const tableBody = document.getElementById('ticket-table-body');
        tableBody.innerHTML = '';  // 清空表格内容

        // 遍历返回的工单数据并生成表格行
        data.tickets.forEach(ticket => {
            const row = document.createElement('tr');
            row.innerHTML = `
                     <td>${ticket.id}</td>
                    <td>${ticket.title}</td>
                    <td>${ticket.description}</td>
                    <td>${ticket.submitter}</td>
                    <td>${ticketStatusEnum[ticket.status] || '未知状态'}</td>
                    <td>
                        <button class="btn btn-info btn-sm" onclick="viewTicket(${ticket.id})">查看</button>
                        <button class="btn btn-warning btn-sm" onclick="assignTicket(${ticket.id})">分派</button>
                        <button class="btn btn-danger btn-sm" onclick="closeTicket(${ticket.id})">关闭</button>
                    </td>
                `;
            tableBody.appendChild(row);  // 将行添加到表格中
        });

        // 更新分页控件
        const pagination = document.getElementById('pagination');
        pagination.innerHTML = '';
        const totalPages = Math.ceil(data.total_count / data.page_size);  // 计算总页数
        for (let i = 1; i <= totalPages; i++) {
            const pageItem = document.createElement('li');
            pageItem.className = 'page-item' + (i === page ? ' active' : '');  // 当前页加上 'active' 类
            pageItem.innerHTML = `<button class="page-link" onclick="fetchTickets(${i})">${i}</button>`;
            pagination.appendChild(pageItem);  // 将页码按钮添加到分页控件中
        }
    }

    // 示例功能函数 - 查看工单
    async function viewTicket(ticketId) {
        try {
            const response = await fetch(`/ticket/${ticketId}`);
            if (response.ok) {
                const data = await response.json();
                const ticket = data.ticket;

                // 填充模态框数据
                document.getElementById('ticket-id').textContent = ticket.id;
                document.getElementById('ticket-title').textContent = ticket.title;
                document.getElementById('ticket-description').textContent = ticket.description;
                document.getElementById('ticket-submitter').textContent = ticket.submitter;
                document.getElementById('ticket-assignee').textContent = ticket.assignee;
                document.getElementById('ticket-status').textContent = ticketStatusEnum[ticket.status] || '未知状态';
                document.getElementById('ticket-create-time').textContent = ticket.f_create_time.replace('T', ' ');
                document.getElementById('ticket-update-time').textContent = ticket.f_update_time.replace('T', ' ');
                document.getElementById('ticket-recover').value = ticket.recover || ''; // 设置回复内容

                // 显示模态框
                const viewTicketModal = new bootstrap.Modal(document.getElementById('view-ticket-modal'));
                viewTicketModal.show();

                // 保存按钮事件绑定
                document.getElementById('save-recover-btn').onclick = async function () {
                    const recoverContent = document.getElementById('ticket-recover').value;

                    const saveResponse = await fetch(`/update_recover`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                        },
                        body: JSON.stringify({
                            ticket_id: ticketId,
                            recover: recoverContent,
                        }),
                    });

                    const saveResult = await saveResponse.json();
                    alert(saveResult.message);
                    if (saveResult.success) {
                        viewTicketModal.hide(); // 关闭模态框
                        fetchTickets(); // 刷新工单列表
                    }
                };
            } else {
                alert("未找到该工单！");
            }
        } catch (error) {
            alert("获取工单详情时出错，请稍后再试！");
        }
    }

    // 示例功能函数 - 分派工单
    async function assignTicket(ticketId) {
        const assignee = prompt("请输入分派人姓名：");
        if (!assignee) {
            alert("必须输入分派人！");
            return;
        }

        try {
            const response = await fetch(`${apiBase}/assign_ticket`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ticket_id: ticketId,
                    assignee: assignee
                })
            });

            const result = await response.json();
            if (response.ok) {
                alert(result.message);
                fetchTickets(currentPage);  // 保持当前页
            } else {
                alert("分派工单失败: " + result.message);
            }
        } catch (error) {
            alert("请求失败，请稍后再试！");
        }
    }

    // 示例功能函数 - 关闭工单
    async function closeTicket(ticketId) {
        const confirmClose = confirm("确定要关闭该工单吗？");
        if (!confirmClose) {
            return;
        }

        try {
            const response = await fetch(`${apiBase}/close_ticket`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    ticket_id: ticketId
                })
            });

            const result = await response.json();
            if (response.ok) {
                alert(result.message);
                fetchTickets(currentPage);  // 保持当前页
            } else {
                alert("关闭工单失败: " + result.message);
            }
        } catch (error) {
            alert("请求失败，请稍后再试！");
        }
    }

    // 示例功能函数 - 创建工单
    async function createTicket() {
        // 获取表单数据
        const title = document.getElementById('title').value;
        const description = document.getElementById('description').value;
        const submitter = document.getElementById('submitter').value;

        // 检查表单是否填写完整
        if (!title || !description || !submitter) {
            alert("请填写所有字段！");
            return;
        }

        // 向后端发送请求
        try {
            const response = await fetch(`${apiBase}/create_ticket`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    title: title,
                    description: description,
                    submitter: submitter
                })
            });

            const result = await response.json();
            if (response.ok) {
                alert(result.message);
                // 使用 Bootstrap 5 原生 API 隐藏模态框
                // const createTicketModal = new bootstrap.Modal(document.getElementById('create-ticket-modal'));
                // createTicketModal.hide();  // 关闭模态框
                // 使用 Bootstrap 5 原生 API 隐藏模态框
                const createTicketModal = bootstrap.Modal.getInstance(document.getElementById('create-ticket-modal'));
                createTicketModal.hide();  // 关闭模态框
                fetchTickets();  // 刷新工单列表
            } else {
                alert("创建工单失败: " + result.message);
            }
        } catch (error) {
            alert("请求失败，请稍后再试！");
        }
    }

    // 新的分页逻辑代码
    let currentPage = 1;  // 当前页码
    let totalPages = 0;  // 总页数

    // 更新分页控件
    function updatePagination(data) {
        const pageSelect = document.getElementById('page-select');
        const totalPagesElem = document.getElementById('total-pages');
        const prevPageBtn = document.getElementById('prev-page-btn');
        const nextPageBtn = document.getElementById('next-page-btn');

        totalPages = Math.ceil(data.total_count / data.page_size);  // 计算总页数
        totalPagesElem.textContent = totalPages;

        // 更新页码选择下拉框
        pageSelect.innerHTML = '';
        for (let i = 1; i <= totalPages; i++) {
            const option = document.createElement('option');
            option.value = i;
            option.textContent = i;
            if (i === currentPage) option.selected = true;  // 当前页选中
            pageSelect.appendChild(option);
        }

        // 控制“上一页”和“下一页”按钮状态
        prevPageBtn.disabled = currentPage === 1;
        nextPageBtn.disabled = currentPage === totalPages;
    }

    // 改变页码
    function changePage(page) {
        currentPage = parseInt(page, 10);
        fetchTickets(currentPage);
    }

    // 上一页逻辑
    document.getElementById('prev-page-btn').addEventListener('click', () => {
        if (currentPage > 1) {
            currentPage--;
            fetchTickets(currentPage);
        }
    });

    // 下一页逻辑
    document.getElementById('next-page-btn').addEventListener('click', () => {
        if (currentPage < totalPages) {
            currentPage++;
            fetchTickets(currentPage);
        }
    });

    // 在获取工单时调用分页更新
    async function fetchTickets(page = 1) {
        currentPage = page;  // 更新当前页码
        const statusFilter = document.getElementById('ticket-status-filter').value;
        const response = await fetch(`${apiBase}/tickets_paginated?page=${page}&status=${statusFilter}`);
        const data = await response.json();
        const tableBody = document.getElementById('ticket-table-body');
        tableBody.innerHTML = '';

        data.tickets.forEach(ticket => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${ticket.id}</td>
                <td>${ticket.title}</td>
                <td>${ticket.description}</td>
                <td>${ticket.submitter}</td>
                <td>${ticketStatusEnum[ticket.status] || '未知状态'}</td>
                <td>
                    <button class="btn btn-info btn-sm" onclick="viewTicket(${ticket.id})">查看</button>
                    <button class="btn btn-warning btn-sm" onclick="assignTicket(${ticket.id})">分派</button>
                    <button class="btn btn-danger btn-sm" onclick="closeTicket(${ticket.id})">关闭</button>
                </td>
            `;
            tableBody.appendChild(row);
        });

        updatePagination(data);  // 更新分页控件
    }

    // 监听“保存”按钮，触发创建工单操作
    document.getElementById('save-ticket-btn').addEventListener('click', createTicket);

    // 点击“刷新工单列表”按钮时调用 fetchTickets 函数
    document.getElementById('refresh-btn').addEventListener('click', () => fetchTickets());

    // 页面加载时默认显示第一页的工单列表
    fetchTickets();

    // 监听“创建工单”按钮，触发模态框显示
    document.getElementById('create-ticket-btn').addEventListener('click', () => {
        const createTicketModal = new bootstrap.Modal(document.getElementById('create-ticket-modal'));
        createTicketModal.show();  // 显示模态框
    });

    //

</script>
</body>
</html>
